<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            position: absolute;
            left: 0;
            top: 0;
            width: 100px;
            height: 100px;
            background-color: green;
            cursor: move;
        }

        .inner {
            width: 50px;
            height: 50px;
            margin-left: 20px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="inner">

        </div>
    </div>
    <script>
        var boxEl = document.querySelector('.box');
        // 1. 监听鼠标按下去
        boxEl.onmousedown = function (e) {
            var event = e || window.event;
            // 按下去的时候就获取鼠标初始位置
            // event.offsetX 指的是触发事件的当前元素边距 所以如果box被嵌套则会出问题
            // offsetX = pageX - el.offsetLeft 
            // var startPointX = event.offsetX;
            // var startPointY = event.offsetY;
            var startPointX = event.pageX - boxEl.offsetLeft;
            var startPointY = event.pageY - boxEl.offsetTop;
            // 2. 监听鼠标移动
            document.onmousemove = function (e) {
                var event = e || window.event;
                // 随着移动获取鼠标相对页面的坐标
                var currentX = event.pageX;
                var currentY = event.pageY;
                // 赋值给box
                // 发现鼠标按下去的位置应该减去
                boxEl.style.left = currentX - startPointX + 'px';
                boxEl.style.top = currentY - startPointY + 'px';
            }

            // 3. 松开鼠标 清除move事件
            boxEl.onmouseup = function () {
                // 回顾 两种清除事件的方式
                document.onmousemove = null;
            }
        }

    </script>
</body>

</html>